<template>
  <div class="app-container calendar-list-container" id="smialClick" style="height: 100%;">
    <div class="filter-container">
      <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item" placeholder="标题" v-model="listQuery.title">
      </el-input>
      <el-button class="filter-item" type="primary" v-waves icon="el-icon-search" @click="handleFilter">查询</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" @click="handleCreate" type="primary" icon="el-icon-edit">新增</el-button>
      <el-button class="filter-item" type="primary" :loading="downloadLoading" v-waves icon="el-icon-download" @click="handleDownload">导出</el-button>
    </div>

    <el-table :data="list" v-loading="listLoading" element-loading-text="给我一点时间"
              @row-click="currentClick"
              highlight-current-row style="width: 100%">
      <el-table-column width="150px" align="center" label="商户名称">
        <template slot-scope="scope">
          <span>{{scope.row.merchantName}}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="150px" label="商户标题">
        <template slot-scope="scope">
          <span class="link-type" @click="handleUpdate(scope.row)">{{scope.row.title}}</span>
          <el-tag>{{scope.row.merchantTitle}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" :label="$t('table.actions')" width="230" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button size="mini" type="success" @click="handleModifyStatus(scope.row,'published')">通过
          </el-button>
          <el-button size="mini" @click="handleModifyStatus(scope.row,'draft')">普通
          </el-button>
          <el-button size="mini" type="danger" @click="handleModifyStatus(scope.row,'deleted')">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="listQuery.page" :page-sizes="[10,20,30, 50]" :page-size="listQuery.limit" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

    <el-dialog title="修改" :visible.sync="dialogFormVisible">
      <el-form :rules="rules" ref="dataForm" :model="temp" label-position="left" label-width="70px" style='width: 400px; margin-left:50px;'>
        <el-form-item label="类型" prop="type">
          <el-select class="filter-item" v-model="temp.type" placeholder="Please select">
            <el-option v-for="item in  calendarTypeOptions" :key="item.key" :label="item.display_name" :value="item.key">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="时间" prop="timestamp">
          <el-date-picker v-model="temp.timestamp" type="datetime" placeholder="Please pick a date">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="标题" prop="title">
          <el-input v-model="temp.title"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="createData">确定</el-button>
        <!--<el-button v-else type="primary" @click="updateData">{{$t('table.confirm')}}</el-button>-->
      </div>
    </el-dialog>

    <el-form label-position="left" inline id="lashan"
             v-if="pullBloor"
             v-loading="loading2"
             :model="currentRow"
             ref="currentRow"
             class="demo-table-expand hiddenForm">
      <content>
        <div style="width: 100%;text-align: center;margin-bottom: 5px;height: 36px;">
          <el-button style="float: left;padding: 5px 15px"><i
            style="font-size: x-large;vertical-align: sub" class="fa fa-angle-left" aria-hidden="true"></i>上一条
          </el-button>
          <el-button>临时保存</el-button>
          <el-button style="float: right;padding: 5px 15px">下一条<i
            style="font-size: x-large;vertical-align: sub" class="fa fa-angle-right" aria-hidden="true"></i></el-button>
        </div>
        <div
          style="width: 100%;text-align: center;margin-bottom: 5px;border-bottom: 1px solid #D9D9D9;border-top: 1px solid #D9D9D9;padding: 10px 0">
          <span>待签署</span>
        </div>
        <el-row>
          <el-col :span="12" style="height: 43px;">
            <el-form-item label="申请编号：">
              <span>11111</span>
            </el-form-item>
          </el-col>
          <el-col :span="12" style="height: 43px;">
            <el-form-item label="每月租金：" prop="monthlyRent" id="monthRen">
              <el-input>212111</el-input>
            </el-form-item>

          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12" style="height: 43px;">
            <el-form-item label="租客姓名：">
              <span>呵呵</span>
            </el-form-item>
          </el-col>
          <el-col :span="12" style="height: 43px;">
            <el-form-item label="租客姓名：">
              <span>呵呵</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12" style="height: 43px;">
            <el-form-item label="手机号码：">
              <span>212121</span>
            </el-form-item>
          </el-col>
          <el-col :span="12" style="height: 43px;">
            <el-form-item label="租期合计：">
              <span>212112</span>
            </el-form-item>

          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12" style="height: 43px;">
            <el-form-item label="身份证号：">
              <span>212121</span>
            </el-form-item>
          </el-col>

          <el-col :span="12" style="height: 43px;">
            <el-form-item label="尾款合计：">
              <span>212121</span>
            </el-form-item>
          </el-col>
        </el-row>
        <hr style="border-bottom-color: #d9d9d9; border-top: none;">
        <el-row style="padding-bottom: 80px">
          <el-tabs>
            <el-tab-pane label="还款账单" name="order">
              <el-table
                highlight-current-row
                tooltip-effect="dark">
                <el-table-column
                  min-width="140"
                  prop="paymentDueDate"
                  label="应还款日期">
                  <template slot-scope="scope">
                    321312
                  </template>
                </el-table-column>
                <el-table-column
                  min-width="100"
                  prop="amount"
                  label="账单金额">
                  <template slot-scope="scope">
                    321312
                  </template>
                </el-table-column>
                <el-table-column
                  min-width="130"
                  prop="serviceFee"
                  label="手续费">
                  <template slot-scope="scope">
                    321312
                  </template>
                </el-table-column>
                <el-table-column
                  min-width="130"
                  prop="overdueFee"
                  label="逾期费">
                  <template slot-scope="scope">
                    32132
                  </template>
                </el-table-column>
                <el-table-column
                  min-width="180"
                  prop="status"
                  label="账单状态">
                  <template slot-scope="scope">
                    3211
                  </template>
                </el-table-column>
                <el-table-column
                  min-width="130"
                  prop="monthlyRent"
                  label="实际还款日期">
                  <template slot-scope="scope">
                    32131
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
            <el-tab-pane label="房屋信息" name="houseInfo" id="houseInfo">
              <el-row>
                <el-col>
                  <el-form-item label="飒飒撒所" prop="address">
                    <el-input placeholder="详细地址"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col>
                  <el-form-item label="台账号码：" prop="apartmentNo">
                    <el-input placeholder="请输入台账号"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-tab-pane>
          </el-tabs>
        </el-row>
        <el-row  style="opacity: .5;position: fixed;bottom: 0;width: 98%;">
          <hr style="border-bottom-color: #d9d9d9; border-top: none;opacity: 1">
          <el-col :span="6" style="height: 40px;">
            <el-form-item label="经纪人：">
              <span>2121</span>
            </el-form-item>
          </el-col>
          <el-col :span="6" style="height: 40px;">
            <el-form-item label="联系方式：">
              <span>2112</span>
            </el-form-item>
          </el-col>
          <el-col :span="6" style="height: 40px;">
            <el-form-item label="申请日期：">
              <span>2121</span>
            </el-form-item>
          </el-col>
        </el-row>
      </content>
    </el-form>
  </div>
</template>

<script>
  import { createArticle, updateArticle, getMerchant } from '@/api/article'
  import waves from '@/directive/waves' // 水波纹指令
  import { parseTime } from '@/utils'
  import Vue from 'vue'

  const calendarTypeOptions = [
    { key: 'CN', display_name: 'China' },
    { key: 'US', display_name: 'USA' },
    { key: 'JP', display_name: 'Japan' },
    { key: 'EU', display_name: 'Eurozone' }
  ]

  // arr to obj ,such as { CN : "China", US : "USA" }
  const calendarTypeKeyValue = calendarTypeOptions.reduce((acc, cur) => {
    acc[cur.key] = cur.display_name
    return acc
  }, {})

  export default {
    name: 'complexTable',
    directives: {
      waves
    },
    data() {
      return {
        currentRow: {

        },
        loading2: false,
        pullBloor: false, // 拉扇层是否显示
        list: null,
        total: null,
        listLoading: true,
        listQuery: {
          page: 1,
          limit: 20,
          importance: undefined,
          title: undefined,
          type: undefined,
          sort: '+id'
        },
        importanceOptions: [1, 2, 3],
        calendarTypeOptions,
        sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
        statusOptions: ['published', 'draft', 'deleted'],
        showReviewer: false,
        temp: {
          id: undefined,
          importance: 1,
          remark: '',
          timestamp: new Date(),
          title: '',
          type: '',
          status: 'published'
        },
        dialogFormVisible: false,
        dialogStatus: '',
        textMap: {
          update: 'Edit',
          create: 'Create'
        },
        pvData: [],
        rules: {
          type: [{ required: true, message: 'type is required', trigger: 'change' }],
          timestamp: [{ type: 'date', required: true, message: 'timestamp is required', trigger: 'change' }],
          title: [{ required: true, message: 'title is required', trigger: 'blur' }]
        },
        downloadLoading: false
      }
    },
    filters: {
      statusFilter(status) {
        const statusMap = {
          published: 'success',
          draft: 'info',
          deleted: 'danger'
        }
        return statusMap[status]
      },
      typeFilter(type) {
        return calendarTypeKeyValue[type]
      }
    },
    created() {
      this.init()
    },
    methods: {
      init() {
        const that = this
        // 点击关闭拉扇层
        Vue.nextTick(function() {
          document.getElementById('smialClick').onclick = function(e) {
            if (e.target === this) {
              that.hiddenClass()
            }
          }
          document.getElementsByClassName('navbar')[0].onclick = function() {
            that.hiddenClass()
          }
          document.getElementsByClassName('tags-view-container')[0].onclick = function() {
            that.hiddenClass()
          }
        })
        const obj = {
          page: 0,
          size: 10
        }
        this.listLoading = true
        getMerchant(obj).then(res => {
          this.list = res.data.content
          this.total = res.data.totalElements
          this.listLoading = false
        })
      },
      // 点击一行
      currentClick(val) {
        this.pullBloor = true
        // TODO 先去掉遮罩层，分析原因可能是因为拉扇层还没有显示，就点击
        // this.cover = true;
        Vue.nextTick(function() {
          document.querySelector('.hiddenForm').className = 'daveShow hiddenForm el-form demo-table-expand el-form--label-left el-form--inline'
        })
      },
      // 隐藏右侧内容
      hiddenClass() {
        const that = this
        clearTimeout(a) // 清除延时
        this.cover = false
        if (document.querySelector('.hiddenForm') !== null) {
          document.querySelector('.hiddenForm').className = 'hiddenForm el-form demo-table-expand el-form--label-left el-form--inline'
          var a = setTimeout(function() {
            that.pullBloor = false
          }, 500)
        }
      },
      handleFilter() {
        this.listQuery.page = 1
        this.init()
      },
      handleSizeChange(val) {
        this.listQuery.limit = val
        this.init()
      },
      handleCurrentChange(val) {
        this.listQuery.page = val
        this.init()
      },
      handleModifyStatus(row, status) {
        this.$message({
          message: '操作成功',
          type: 'success'
        })
        row.status = status
      },
      resetTemp() {
        this.temp = {
          id: undefined,
          importance: 1,
          remark: '',
          timestamp: new Date(),
          title: '',
          status: 'published',
          type: ''
        }
      },
      handleCreate() {
        this.resetTemp()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      createData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.temp.id = parseInt(Math.random() * 100) + 1024 // mock a id
            this.temp.author = 'vue-element-admin'
            createArticle(this.temp).then(() => {
              this.list.unshift(this.temp)
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '创建成功',
                type: 'success',
                duration: 2000
              })
            })
          }
        })
      },
      handleUpdate(row) {
        this.temp = Object.assign({}, row) // copy obj
        this.temp.timestamp = new Date(this.temp.timestamp)
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      updateData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            const tempData = Object.assign({}, this.temp)
            tempData.timestamp = +new Date(tempData.timestamp) // change Thu Nov 30 2017 16:41:05 GMT+0800 (CST) to 1512031311464
            updateArticle(tempData).then(() => {
              for (const v of this.list) {
                if (v.id === this.temp.id) {
                  const index = this.list.indexOf(v)
                  this.list.splice(index, 1, this.temp)
                  break
                }
              }
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 2000
              })
            })
          }
        })
      },
      handleDelete(row) {
        this.$notify({
          title: '成功',
          message: '删除成功',
          type: 'success',
          duration: 2000
        })
        const index = this.list.indexOf(row)
        this.list.splice(index, 1)
      },
      handleDownload() {
        this.downloadLoading = true
        import('@/vendor/Export2Excel').then(excel => {
          const tHeader = ['timestamp', 'title', 'type', 'importance', 'status']
          const filterVal = ['timestamp', 'title', 'type', 'importance', 'status']
          const data = this.formatJson(filterVal, this.list)
          excel.export_json_to_excel(tHeader, data, 'table-list')
          this.downloadLoading = false
        })
      },
      formatJson(filterVal, jsonData) {
        return jsonData.map(v => filterVal.map(j => {
          if (j === 'timestamp') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        }))
      }
    }
  }
</script>
<style scoped>
  .hiddenForm {
    min-width: 700px;
    margin-top: -40px;
    box-shadow: -10px 0px 5px #888888;
    padding: 15px;
    overflow-y: scroll;
    width: 65%;
    height: 100%;
    z-index: 999;
    transition: all 0.5s;
    position: absolute;
    top: 40px;
    left: 200%;
  }

  .daveShow {
    min-width: 700px;
    margin-top: -40px;
    box-shadow: -10px 0px 5px #888888;
    padding: 15px;
    overflow-y: scroll;
    width: 65%;
    height: 100%;
    z-index: 999;
    background-color: #fff;
    position: absolute;
    top: 40px;
    left: 33.5%;
  }
</style>
